using System;
using System.Collections.Generic;
using System.Reflection;
using Newtonsoft.Json;
using NExt.Core.Model.Enum;
using System.IO;

namespace NExt.Serialization.JsonNet.Conversion
{
    public class AnonymousObjectConvertor : AbstractJsonConvertor<AnonymousObject>
    {
        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
        {
            AnonymousObject anonymousObject = (AnonymousObject)value;
            writer.WriteStartObject();
            ICollection<AnonymousObject> innerAnonymousObjects = anonymousObject.GetInnerObjects();
            foreach (AnonymousObject innerAnonymousObject in innerAnonymousObjects)
            {
                Type runtimeType = innerAnonymousObject.GetType();
                PropertyInfo[] propertyInfos = runtimeType.GetProperties(BindingFlags.Public | BindingFlags.Instance);

                foreach (PropertyInfo propertyInfo in propertyInfos)
                {
                    MethodInfo methodInfo = propertyInfo.GetGetMethod();
                    string propertyName = propertyInfo.Name;
                    object propertyValue = methodInfo.Invoke(innerAnonymousObject, null);

                    StringWriter stringWriter = new StringWriter();
                    serializer.Serialize(stringWriter, propertyValue);
                    string serializedValue = this.Serialize(serializer, propertyValue);

                    writer.WritePropertyName(propertyName);
                    writer.WriteRawValue(serializedValue);
                }
            }

            writer.WriteEndObject();
        }
    }
}